#include "util.h"
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
//设置文件描述符为非阻塞

int setnonblocking(int fd){

    int old_option=fcntl(fd,F_GETFL);
    int new_option=old_option|O_NONBLOCK;
    fcntl(fd,F_SETFL,new_option);
    return old_option;
}



//将文件描述符fd上的EPOLLIN注册到epfd指示的内核事件表中



 void addfd(int epfd,int fd,bool enable_et){
    struct  epoll_event event;
    event.data.fd=fd;
    event.events=EPOLLIN;
    if(enable_et)
    {
        event.events|=EPOLLET;
    }
    epoll_ctl(epfd,EPOLL_CTL_ADD,fd,&event);
    setnonblocking(fd);
 }

 void lt(epoll_event*events,int number,int epfd,int listenfd){
     char buf[BUFFER_SIZE];
     for(int i=0;i<number;i++)
     {

        int sockfd=events[i].data.fd;
        //有新连接进入
        if(sockfd==listenfd){
            struct sockaddr_in client_addr;
            //struct sockadddr_in client_addr;
            socklen_t len=sizeof(client_addr);
            int cfd=accept(listenfd,(struct sockaddr*)&client_addr,&len);
            addfd(epfd,cfd,false);//对客户端禁止使用ET
        }else if(events[i].data.fd&EPOLLIN){
            //
            std::cout<<"event trigger once"<<std::endl;
            memset(buf,'\0',BUFFER_SIZE);
            int ret=recv(sockfd,buf,BUFFER_SIZE-1,0);
            if(ret<=0){

                close(sockfd);
                continue;
            }
            std::cout<<"get "<<ret<<"bytes"<<std::endl;
            std::cout<<"message:"<<buf<<std::endl;
        }else{


            std::cout<<"something heppend"<<std::endl;

        }

     }




 }